package com.codehacker.job.mallservice.controller;

import com.alibaba.fastjson.JSON;
import com.codehacker.job.mallservice.dao.UserMapper;
import com.codehacker.job.mallservice.dto.ResponseDTO;
import com.codehacker.job.mallservice.entity.User;
import com.codehacker.job.mallservice.entity.UserExample;
import com.codehacker.job.mallservice.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * UserController
 *
 * @author zhuyuwei
 * @date 26/07/2017
 */
@Controller
@RequestMapping("/api/user")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserMapper userMapper;

    @RequestMapping("/sign/in")
    @ResponseBody
    public ResponseDTO<User> signIn(@RequestBody User user) {
        logger.info("param {}", JSON.toJSONString(user));
        ResponseDTO<User> result = new ResponseDTO<User>();
        UserExample example = new UserExample();
        example.createCriteria().andNameEqualTo(user.getName())
                .andPasswordEqualTo(user.getPassword());
        List<User> users = userMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(users)) {
            user.setToken(MD5Util.MD5(String.valueOf(new Random().nextInt(10))));
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            userMapper.insertSelective(user);
        }
        result.getData().getItems().add(users.get(0));
        result.getMeta().setCode(0);
        logger.info("result {}", JSON.toJSONString(result));
        return result;
    }
}

